package com.jinzhi.oss.controller;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Dict;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.oss.domain.FileDO;
import com.jinzhi.oss.service.FileService;
import com.jinzhi.oss.service.OssService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <pre>
 * 文件上传
 * </pre>
 * <p>
 * <small> 2018年3月23日 | Aron</small>
 */
@Controller
@RequestMapping("/common/sysFile")
public class FileController extends BaseController {

    @Autowired
    private FileService sysFileService;

    @Autowired
    private OssService ossService;


    private  String fastIp;


    private  String fastProt;


    private  String fastGroup;

    @Autowired
    private  DictService dictService;

    public void fatInit(){

        Map map =new HashMap();
        map.put("type","fastdfs_group");
        map.put("name","fastdfs_group");
        fastGroup = dictService.selDicBy(map);

        map =new HashMap();
        map.put("type","fastdfs_prot");
        map.put("name","fastdfs_prot");
        fastProt = dictService.selDicBy(map);

        map =new HashMap();
        map.put("type","fastdfs_ip");
        map.put("name","fastdfs_ip");
        fastIp = dictService.selDicBy(map);

    }


    //UPLOAD_PATH = ip + 服务端口 + 分组 + upload http://192.168.1.191:9999/group1/upload
    private String UPLOAD_PATH;


    @GetMapping()
    @RequiresPermissions("oss:file:file")




    String sysFile(Model model) {
        return "common/file/file";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("oss:file:list")
    public Result<Page<FileDO>> list(FileDO fileDTO) {
        Wrapper<FileDO> wrapper = new EntityWrapper<FileDO>(fileDTO);
        Page<FileDO> page = sysFileService.selectPage(getPage(FileDO.class), wrapper);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("oss:file:add")
    String add() {
        return "common/sysFile/add";
    }

    @GetMapping("/edit")
    @RequiresPermissions("oss:file:update")
    String edit(Long id, Model model) {
        FileDO sysFile = sysFileService.selectById(id);
        model.addAttribute("sysFile", sysFile);
        return "common/sysFile/edit";
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("oss:file:info")
    public Result<FileDO> info(@PathVariable("id") Long id) {
        FileDO sysFile = sysFileService.selectById(id);
        return Result.ok(sysFile);
    }

    /**
     * 保存
     */
    @Log("添加文件")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("oss:file:add")
    public Result<String> save(FileDO sysFile) {
        sysFileService.insert(sysFile);
        return Result.ok();
    }

    /**
     * 修改
     */
    @Log("更新文件")
    @RequestMapping("/update")
    @RequiresPermissions("oss:file:update")
    public Result<String> update(@RequestBody FileDO sysFile) {
        sysFileService.updateById(sysFile);
        return Result.ok();
    }

    /**
     * 删除
     */
    @Log("删除文件")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("oss:file:remove")
    public Result<String> remove(Long id) {
        sysFileService.deleteById(id);
        return Result.ok();
    }

    /**
     * 删除
     */
    @Log("批量删除文件")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("oss:file:remove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        sysFileService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }




    //阿里云
//    @Log("上传文件")
//    @ResponseBody
//    @PostMapping("/upload")
////    @RequiresPermissions("oss:file:add")
//    Result<String> upload(@RequestParam("file") MultipartFile file) {
//        String url  =ossService.uploadFileOss(file);
//        return Result.ok(url);
//    }






    //本地对象存储
    @Log("上传文件")
    @ResponseBody
    @PostMapping("/upload")
    Result<String> upload(@RequestParam("file") MultipartFile file) {

        fatInit(); //初始化

        UPLOAD_PATH = "http://" + fastIp + ":" + fastProt + fastGroup;  //http://192.168.1.191:9999/group1/upload

        String url = "";
        try {
            InputStreamResource isr = new InputStreamResource(file.getInputStream(),
                    file.getOriginalFilename());

            Map<String, Object> params = new HashMap<>();
            params.put("file", isr);
            params.put("path", "86501729");
            params.put("output", "json");
            String resp = HttpUtil.post(UPLOAD_PATH, params);
            Console.log("resp: {}", resp);


            //取出上传结果
            Map map = JSON.parseObject(resp, Map.class);
            //取出最终的url路径
            url = (String) map.get("url");
            //将localhost替换为fast服务所在的ip地址
            url = url.replace("localhost",fastIp);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.ok(url);
    }

}
